<template>
  <div>
    <el-row style="margin-top: 10px">
    <el-col :span="20" style="text-align: left;" >
      <el-form ref="form" :model="searchForm" :inline="true">
        <el-form-item label="顾客名称:">
          <el-input placeholder="根据顾客名称查找" v-model="searchForm.keyWords" />
        </el-form-item>
        <el-button icon="el-icon-search" circle @click="search" />
        <el-button type="primary" icon="el-icon-plus" size="small" style="margin-left: 20px;
  margin-top: 5px;" @click="newAdd">新增
        </el-button>
        <el-button type="danger" v-if="selections.length>0" icon="el-icon-delete" size="small" style="
  margin-top: 5px;" @click="batchDeleteByIds">删除
        </el-button>
      </el-form>
    </el-col>
    </el-row>

    <el-row>
    <el-card class="box-card" style="margin: 5px;">
      <div slot="header" class="clearfix">
        <span>顾客列表</span>
      </div>
      <!-- 顾客列表-->
      <el-table :data="customers" stripe style="width: 100%" @selection-change="handleSelectionChange"
                @row-dblclick="updateSubmit" max-height="650" border>
        <el-table-column type="selection" width="50"/>
        <el-table-column prop="name" label="顾客姓名" align="center"/>
        <el-table-column prop="sex" label="顾客性别" align="center" :formatter="formatGender"/>
        <el-table-column prop="age" label="顾客年龄" align="center" />
        <el-table-column prop="tele" label="顾客电话" align="center"/>
        <el-table-column prop="car" label="顾客车名" align="center"/>
        <el-table-column prop="carNum" label="顾客车牌号" align="center"/>
        <el-table-column prop="address" label="顾客地址" align="center"/>
        <el-table-column prop="createTime" label="创建时间" align="center"/>
        <el-table-column prop="vip.grade" label="会员等级" align="center"/>
      </el-table>
      <!-- 分页工具条 -->
      <div style="margin-top: 10px" class="block">
        <el-pagination
          :page-sizes="pageSizes"
          :page-size="pageSize"
          :current-page="currentPage"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    </el-row>

    <!-- 添加/编辑 界面 -->
    <el-dialog title="VIP信息" :visible.sync="dialogVisible" width="30%">
      <el-form :model="editForm"
               :rules="rules"
               ref="ruleForm"
               label-width="100px" class="demo-ruleForm">

        <el-form-item label="顾客姓名" prop="name">
          <el-input v-model="editForm.name"/>
        </el-form-item>

        <el-form-item label="顾客性别" prop="sex">
          <el-radio-group v-model="editForm.sex">
            <el-radio-button label="男"/>
            <el-radio-button label="女"/>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="顾客年龄" prop="age">
          <el-input v-model="editForm.age"/>
        </el-form-item>

        <el-form-item label="顾客电话" prop="tele">
          <el-input v-model="editForm.tele"/>
        </el-form-item>

        <el-form-item label="顾客车名" prop="car">
          <el-input v-model="editForm.car"/>
        </el-form-item>

        <el-form-item label="顾客车牌号" prop="carNum">
          <el-input v-model="editForm.carNum"/>
        </el-form-item>

        <el-form-item label="顾客地址" prop="address">
          <el-input v-model="editForm.address"/>
        </el-form-item>

<!--        <el-form-item label="创建时间" prop="create_time">
          <el-input v-model="editForm.createTime"/>
        </el-form-item>-->

        <el-form-item label="会员等级" prop="vip">
          <el-select @focus="loadVip" v-model="editForm.vip.id" clearable placeholder="请选择">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitForm('ruleForm')">确认提交</el-button>
          <el-button @click="resetForm('ruleForm')">重置</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

  </div>

</template>
<script>
  export default {
    data() {
      return {
        customers: [],
        pageNo: 1,
        pageSize: 10,
        total: 0,
        pageSizes: [5, 10, 15, 20],
        currentPage:1,
        keyWord:"",

        // 添加/编辑表单属性
        editForm: {
          id: '',
          name: '',
          sex:'男',
          age:'',
          tele:'',
          car:'',
          carNum:'',
          address:'',
          vip:{
            id:'',
            name:'',
            cost:'',
            discount:''
          }
        },
        vipId:'',

        dialogVisible: false,

        // 验证规则
        rules: {
          name: [
            {required: true, message: '请输入顾客姓名', trigger: 'blur'},
          ],
          age: [
            {required: true, message: '请输入顾客年龄', trigger: 'blur'},
          ],
          tele: [
            {required: true, message: '请输入顾客电话', trigger: 'blur'},
          ],
          car: [
            {required: true, message: '请输入顾客车名', trigger: 'blur'},
          ],
          carNum: [
            {required: true, message: '请输入顾客车牌号', trigger: 'blur'},
          ],
          address: [
            {required: true, message: '请输入顾客地址', trigger: 'blur'},
          ]
        },

        //复选框选中行
        selections: [],

        //搜索框中
        searchForm:{
          keyWords:''
        },

        //会员等级下拉列表框数据
        options: [],
        value: ''
      }
    },
    methods: {
      //加载列表数据
      getCustomers() {
        //获取参数
          //当前页码
          //页码最大记录数
          //搜索关键词
        let params = {
          pageNo:this.currentPage,
          pageSize:this.pageSize,
          keyWord:this.searchForm.keyWords
        };

        //发送请求到后台查询数据axios
        this.$http.post('/customer/findForList',params).then(res => {
          this.customers = res.data.data.result;
          this.currentPage=res.data.data.pageNo;
          this.total=res.data.data.total;
        })
      },

      //页码大小发生变化
      handleSizeChange(pageSize) {
        this.pageSize = pageSize;
        this.getCustomers();
      },

      //当前页码发生变化
      handleCurrentChange(currentPage) {
        this.currentPage = currentPage;
        this.getCustomers();
      },

      //添加按钮
      newAdd() {
        this.editForm.id="";  //清空编辑留下的id
        this.dialogVisible = true;
        this.$nextTick(() => {
          this.$refs['ruleForm'].resetFields();//重置表单
          //清空上一次选中的会员等级
          this.editForm.vip.id = '';
        })
      },

      //修改按钮
      updateSubmit(row) {
        this.dialogVisible = true;
        this.$nextTick(() => {
          this.$refs['ruleForm'].resetFields();//重置表单
          this.editForm = $.extend({}, row);  //回显
          this.editForm.sex = row.sex ? '男' : '女';
          this.loadVip();
          this.editForm.vip.id = row.vip.id;
        })
      },

      //提交表单
      submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {  //如果验证通过

            this.formatGenderOrgin();  //格式化性别为数据库需要的值

            let url = "/customer/insert";
            //修改
            if (this.editForm.id){
                url = "/customer/update";   //如果id有值为修改请求

              //克隆表单中的数据
              let params = Object.assign({}, this.editForm);

              this.$http.put(url,params)
                .then((res)=>{
                  if(res.data.success){
                    this.$message({
                      showClose: true,
                      message: '修改成功',
                      type: 'success'
                    });
                    this.dialogVisible = false;
                    this.getCustomers();
                  }else{
                    this.$message({
                      showClose: true,
                      message: '修改失败【'+res.message+"】",
                      type: 'error'
                    });
                  }
                })
                .catch((error)=>{
                  this.$message({
                    showClose: true,
                    message: '操作失败【'+error.message+"】,请联系攻城狮",
                    type: 'error'
                  });
                })
            }else{      //添加

              //克隆表单中的数据
              var params = Object.assign({}, this.editForm);

              this.$http.post(url,params)
                .then((res)=>{
                  if(res.data.success){
                    this.$message({
                      showClose: true,
                      message: '添加成功',
                      type: 'success'
                    });
                    this.dialogVisible = false;
                    this.getCustomers();
                  }else{
                    this.$message({
                      showClose: true,
                      message: '添加失败【'+res.message+"】",
                      type: 'error'
                    });
                  }
                })
                .catch((error)=>{
                  this.$message({
                    showClose: true,
                    message: '操作失败【'+error.message+"】,请联系攻城狮",
                    type: 'error'
                  });
                })
              }
          }
        });
      },

      //重置表单
      resetForm() {
        this.$nextTick(() => {
          this.$refs['ruleForm'].resetFields();/*清空*/
        })
      },

      //当选中的行改变时 参数为当前行
      handleSelectionChange(selection) {
        this.selections = selection;
      },

      //根据选中行删除数据
      batchDeleteByIds(){

        //遍历选中所有行,并将id值组成数组
        let ids = this.selections.map(item=>item.id);

        //将这个数组作为对象中的数组
        let params = {"ids":ids};

        //删除数据
          this.$http.post("/customer/batchDeleteByIds",params)
            .then((res)=>{
              this.$confirm('是否删除', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
              }).then(() => {
                if(res.data.success){
                  this.$message({
                    showClose: true,
                    message: '删除成功',
                    type: 'success'
                  });
                  this.dialogVisible = false;
                  this.getCustomers();
                }else{
                  this.$message({
                    showClose: true,
                    message: '删除失败【'+res.message+"】",
                    type: 'error'
                  });
                }
              });
            })
            .catch((error)=>{
              this.$message({
                showClose: true,
                message: '操作失败【'+error.message+"】,请联系攻城狮",
                type: 'error'
              });
            })
        },

      //搜索
      search(){
        this.currentPage = 1;
        this.getCustomers();
      },

      //格式化性别
      formatGender(column,row){
        return column.sex ? "男" : "女";
      },

      //提交表单转换性别
      formatGenderOrgin(){
        this.editForm.sex = this.editForm.sex === "男" ? 0 : 1;
      },

      //加载会员等级数据
      loadVip(){
        this.$http.get("/vip/findAll").then((result)=>{
          let data = result.data.data;
          //转换为下拉框需要数据格式
          let newArr = data.map(obj => {
            return {
              label: obj.name,
              value: obj.id
            }});
          this.options = newArr;
        }).catch((error)=>{
          this.$message({
            showClose: true,
            message: '【加载失败】'+error.message+',请联系攻城狮',
            type: 'error'
          });
        })
      }

    },
    mounted() {
      this.getCustomers();
    }
  }
</script>
